package cn.itcast.service.impl;

import cn.itcast.mapper.*;
import cn.itcast.pojo.*;
import cn.itcast.service.orderService;
import cn.itcast.util.CommonUtil;
import cn.itcast.mapper.orderMapper;
import cn.itcast.mapper.orderItemMapper;
import cn.itcast.util.DateUtils;
import cn.itcast.util.ResponseEntity;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static cn.itcast.util.OrderNumber.getOrderIdByTime;

/**
 * @Description: ${用户订单serviceImpl}
 * @return ${return_type}
 * @throws
 * @author 徐威
 * @date 2019/6/3 10:11
 */

@SuppressWarnings("ALL")
@Slf4j
@Service
public class orderServiceImpl implements orderService {
    @Autowired
    private orderMapper orderMapper;

    @Resource
    cn.itcast.mapper.classsifyMapper classsifyMapper;

    @Resource
    orderItemMapper orderItemMapper;

    @Resource
    rechargeMapper rechargeMapper;

    @Resource
    userMapper userMapper;

    @Resource
    accountMapper accountMapper;

    @Resource
    earningsMapper earningsMapper;

    @Resource
    gzhMapper gzhMapper;

    @Resource
    temporaryOrderMapper temporaryOrderMapper;
    @Resource
    temporaryOrderItemMapper temporaryOrderItemMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;



    //2.获取指定条件的用户订单信息
//    @Override
//    public List<order> getAllOrderByCondition(Integer orderStatus,String openId) {
////        orderExample uEx=new orderExample();
////        orderExample.Criteria criteria = uEx.createCriteria();
////        criteria.andOrderStatusEqualTo(orderStatus);
//        return orderMapper.getAllOrderByCondition(orderStatus,openId);
//    }

    //删除单个用户订单
    @Override
    public boolean delectOrder(Integer orderId,String explain) {


        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent("orderId" + orderId, "being");
        stringRedisTemplate.expire("orderId" + orderId,3, TimeUnit.MINUTES);
        if (!ifAbsent){
            return false;
        }

        try {
        //返回是否删除成功
        boolean isdelect = true;

        if(StringUtils.isNotBlank(ObjectUtils.toString(orderId))){
            order order = orderMapper.selectByPrimaryKey(orderId);
            if (order.getOrderState().equals("异常订单")){
                return false;
            }

            if(StringUtils.isNotBlank(ObjectUtils.toString(order.getId()))){
                if (StringUtils.isNotBlank(order.getHorsemanAccount())&&order.getOrderState().equals("进行中")){
                    pushHorseman(order);
                }
                order.setOrderState("异常订单");
                order.setOrderExplain(explain);
                orderMapper.updateByPrimaryKeySelective(order);

                log.debug("开始推送取消订单");
                //推送消息给管理员，提醒派单

                List<String> openIds = new ArrayList<>();

                //冯多飞
                openIds.add("oFPgIw_Xd7UWBrgJpZSyoDPJ4e8Y");
                //杨远量
                openIds.add("oFPgIw8H0Qwdw5xdLLXEstgEwzCk");
                //黄小姐
                openIds.add("oFPgIw3mH9OaK3wMEl9WQMdkYZu4");
                //张松
//                openIds.add("oFPgIwyIjmu5CENT5Oq5W8NlaU7U");
                //肖原
                openIds.add("oFPgIw_D9SUsvqsD_uA7dDxz3eKs");
                //王总
                openIds.add("oFPgIw4m20hoEXIELztoUQM3YdtU");


                //1，配置
                WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
                wxStorage.setAppId("wx8153b9b18ebfa8eb");
                wxStorage.setSecret("c8bf9f0c564f7f44a297054995e6eada");
                String token = gzhMapper.selectByPrimaryKey(3).getAccessToken();
                wxStorage.setAccessToken(token);

                WxMpService wxMpService = new WxMpServiceImpl();
                wxMpService.setWxMpConfigStorage(wxStorage);

                for (int i = 0 ;i<openIds.size() ;i++){

                    WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
                    miniProgram.setAppid("wx51d55df222d9901e");
                    miniProgram.setPagePath("/sendOrder/main?id="+orderId);
                    //2,推送消息
                    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                            .toUser(openIds.get(i))//要推送的用户openid
                            .templateId("l-dV7RL7FPNiMNMZ_mc_3ZdL6RPnIKNLnhVL7wxsf5w")//模版id
                            .miniProgram(miniProgram)
                            .build();
                    //3,如果是正式版发送模版消息，这里需要配置你的信息
                    templateMessage.addData(new WxMpTemplateData("first", "订单取消"));
                    templateMessage.addData(new WxMpTemplateData("keyword1", order.getUserName()));
                    templateMessage.addData(new WxMpTemplateData("keyword2", order.getUserPhone()));
                    templateMessage.addData(new WxMpTemplateData("keyword3", order.getUserArea()));
                    templateMessage.addData(new WxMpTemplateData("keyword4", explain));
                    templateMessage.addData(new WxMpTemplateData("remark", "订单已取消"));

                    //templateMessage.addData(new WxMpTemplateData("name2", value2, color2));
                    try {
                        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    } catch (Exception e) {
                        System.out.println("推送失败：" + e.getMessage());
                        e.printStackTrace();
                    }
                }


            }else {
                isdelect = false;
                log.debug("该订单不存在");
            }
        }else {
            isdelect = false;
            log.debug("传入订单Id为空");
        }
        return isdelect;
        }finally {
            if (!stringRedisTemplate.opsForValue().get("orderId" + orderId).isEmpty()){
                stringRedisTemplate.delete("orderId" + orderId);
            }
        }
    }

    private void pushHorseman(order order) {

        log.debug("开始推送");
        //推送消息给骑手，提醒接单
        String token = gzhMapper.selectByPrimaryKey(2).getAccessToken();


        Template template=new Template();
        template.setTemplate_id("XVZthWMjkc72bcoM7rnYU3q0JkcCMJ2XcCfeBDbirOg");
        String horsemanAccount = order.getHorsemanAccount();
        template.setTouser(horsemanAccount);
        template.setPage("pages/order/main");
        List<TemplateParam> paras=new ArrayList<TemplateParam>();
        paras.add(new TemplateParam("character_string1",order.getOrderNumber()));
        paras.add(new TemplateParam("time2", DateUtils.format(order.getOrderTime())));
        paras.add(new TemplateParam("thing3",order.getOrderExplain()));
        paras.add(new TemplateParam("thing4","用户号码:"+order.getUserPhone()));
        template.setTemplateParamList(paras);
        String requestUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
        requestUrl=requestUrl.replace("ACCESS_TOKEN", token);

        System.out.println(template.toJSON());
        net.sf.json.JSONObject jsonResult= CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());
        if(jsonResult!=null){
            System.out.println(jsonResult);
            int errorCode=jsonResult.getInt("errcode");
            String errorMessage=jsonResult.getString("errmsg");
            if(errorCode==0){
                log.debug("提醒骑手接单Send Success");
            }else{
                log.debug("订阅消息发送失败:"+errorCode+","+errorMessage);
            }
        }

    }


//
//    //4.待收货加入到待评价
//    public boolean updateOrder(order order) {
//        boolean isupdate = false;
//        //判断传入字段是否为空
//        if (StringUtils.isNotBlank(ObjectUtils.toString(order.getOrderId()))){
//            int i = orderMapper.updateByPrimaryKeySelective(order);
//            if(i==1){
//                isupdate = true;
//                log.debug("修改数据成功");
//            }else{
//                log.debug("修改数据有误，不为1条，或者地址Id不存在");
//            }
//        }else {
//            log.debug("地址Id为空");
//        }
//
//        return isupdate;
//    }

    /**
     *
     * @Description:
     * 生成订单
     * @auther: 欧阳辉
     * @date: 9:02 2020/3/17
     * @param: [order]
     * @return: boolean
     *
     */
    @Override
    public boolean addOrder(order order,String productId) {
        String [] id= productId.split(",");
        log.debug(id[0]);

        user user = userMapper.selectByPrimaryKey(order.getOpenId());
        order.setExploitOpenId(user.getExploitOpenId());
        order.setExploitName(user.getExploitName());
        Integer orderTypeId = Integer.parseInt(id[0]);
        String ordertype = "";
        classsify classsifys = classsifyMapper.selectByPrimaryKey(orderTypeId);
        if(classsifys!=null){
            if(classsifys.getFid().equals(133)){
                ordertype = "大件废品";
            }
        }
        order.setOrderType(ordertype);
        order.setOrderform("1");
        int in = orderMapper.insertSelective(order);
        for (int i = 0; i < id.length; i++) {
            classsify classsify = classsifyMapper.selectByPrimaryKey(Integer.parseInt(id[i]));
            orderItem orderItem = new orderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductType(classsify.getName());
            orderItem.setProductImg(classsify.getIcon());
            orderItem.setTodayPrice(classsify.getSettlementPrice());
            orderItem.setUnit(classsify.getMeasure());
            orderItemMapper.insertSelective(orderItem);
        }
        order dataOrder = orderMapper.selectByPrimaryKey(order.getId());
        if(in==1){
            log.debug("开始推送");
            //推送消息给管理员，提醒派单

            List<String> openIds = new ArrayList<>();

            //冯多飞
            openIds.add("oFPgIw_Xd7UWBrgJpZSyoDPJ4e8Y");
            //杨远量
            openIds.add("oFPgIw8H0Qwdw5xdLLXEstgEwzCk");
            //黄小姐
            openIds.add("oFPgIw3mH9OaK3wMEl9WQMdkYZu4");
            //陆荣康
//          openIds.add("oFPgIw9PIVwv02aCzZ2IX8J8CAHM");
            //张松
//            openIds.add("oFPgIwyIjmu5CENT5Oq5W8NlaU7U");
            //高华健
//          openIds.add("oFPgIwyuCjEIJe80pTC2OEoOe234");
            //谢婉怡
//          openIds.add("oFPgIw01Tadi1p3NYhPydRspiFK4");
            //肖原
            openIds.add("oFPgIw_D9SUsvqsD_uA7dDxz3eKs");
            //冯成
//            openIds.add("oFPgIw2-8r79J6aoNrtlhA9EQzn4");
            //王总
//            openIds.add("oFPgIw4m20hoEXIELztoUQM3YdtU");

            //1，配置
            WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
            wxStorage.setAppId("wx8153b9b18ebfa8eb");
            wxStorage.setSecret("c8bf9f0c564f7f44a297054995e6eada");
            String token = gzhMapper.selectByPrimaryKey(3).getAccessToken();
            wxStorage.setAccessToken(token);

            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxStorage);


            for (int i = 0 ;i<openIds.size() ;i++){

                WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
                miniProgram.setAppid("wx51d55df222d9901e");
                miniProgram.setPagePath("/sendOrder/main?id="+dataOrder.getId() );
                //2,推送消息
                WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                        .toUser(openIds.get(i))//要推送的用户openid
                        .templateId("Xc_tnHReR3n1X91cwATTFitTJwgKDGn2YRhpygiA53U")//模版id
                        .miniProgram(miniProgram)
                        .build();
                //3,如果是正式版发送模版消息，这里需要配置你的信息
                templateMessage.addData(new WxMpTemplateData("first", "派单提醒", "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword1", "有用户下单了，请及时派单", "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword2", dataOrder.getUserName(), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword4", dataOrder.getUserPhone(), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword5", dataOrder.getUserArea().substring(dataOrder.getUserArea().indexOf("市")+1,Math.min(dataOrder.getUserArea().indexOf("市")+20,dataOrder.getUserArea().length())), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("remark", "点击派单", "#FF00FF"));
                //templateMessage.addData(new WxMpTemplateData("name2", value2, color2));
                try {
                    wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                } catch (Exception e) {
                    System.out.println("推送失败：" + e.getMessage());
                    e.printStackTrace();
                }
            }



//            String token = gzhMapper.selectByPrimaryKey(3).getAccessToken();
//
//
//            Template template=new Template();
//            template.setTemplate_id("NI3QUdhDLMXCp0AgHryZkirm3gwwf2-YFJV11pJrIko");
//            template.setPage("pages/sendOrder/main?id="+dataOrder.getId());
//            List<TemplateParam> paras=new ArrayList<TemplateParam>();
//            paras.add(new TemplateParam("time3",dataOrder.getOrderVisitTime().substring(0,5)));
//            paras.add(new TemplateParam("character_string1",dataOrder.getOrderNumber()));
//            paras.add(new TemplateParam("thing4","有用户下单了，请及时派单"));
//            paras.add(new TemplateParam("thing2",dataOrder.getUserArea().substring(dataOrder.getUserArea().indexOf("市")+1,Math.min(dataOrder.getUserArea().indexOf("市")+20,dataOrder.getUserArea().length()))));
//            paras.add(new TemplateParam("phone_number5",dataOrder.getUserPhone()));
//            template.setTemplateParamList(paras);
//            String requestUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
//            requestUrl=requestUrl.replace("ACCESS_TOKEN", token);
//
//            List<String> openIds = new ArrayList<>();
//            //欧阳辉
//            openIds.add("osdn25drOI8-6sY9K58zOSCAajOI");
//            //冯多飞
//            openIds.add("osdn25b0tK8-4aguS2xVFa2fxkJc");
//            //肖原
//            openIds.add("osdn25eA1XaqC4oK8sjM-WXIDZwQ");
//            //郭智超
//            openIds.add("osdn25emak1YdPypoWi7XgbMlHiM");
//            //杨远量
//            openIds.add("osdn25R7XC8ovDN14k2vMeV9X5EU");
//            //黄小姐
//            openIds.add("osdn25Ym8McrfpUo-3jVCzKS9700");
//            for (int i = 0 ;i<6 ;i++){
//                template.setTouser(openIds.get(i));
//                net.sf.json.JSONObject jsonResult= CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());
//                if(jsonResult!=null){
//                    System.out.println(jsonResult);
//                    int errorCode=jsonResult.getInt("errcode");
//                    String errorMessage=jsonResult.getString("errmsg");
//                    if(errorCode==0){
//                        log.debug("提醒管理员派单Send Success");
//                    }else{
//                        log.debug("订阅消息发送失败:"+errorCode+","+errorMessage);
//                    }
//                }
//            }
//
//            System.out.println(template.toJSON());

            return true;
        }else {
            return false;
        }
    }

    /**
     *
     * @Description:
     * 生成订单
     * @auther: 欧阳辉
     * @date: 9:02 2020/3/17
     * @param: [order]
     * @return: boolean
     *
     */
    @Override
    public boolean merchantaddOrder(order order,String productId) {
        String [] id= productId.split(",");
        log.debug(id[0]);

        user user = userMapper.selectByPrimaryKey(order.getOpenId());
        order.setExploitOpenId(user.getExploitOpenId());
        order.setExploitName(user.getExploitName());
        Integer orderTypeId = Integer.parseInt(id[0]);
        String ordertype = "";
        classsify classsifys = classsifyMapper.selectByPrimaryKey(orderTypeId);
        if(classsifys!=null){
            if(classsifys.getFid().equals(133)){
                ordertype = "大件废品";
            }
        }
        order.setOrderType(ordertype);
        order.setOrderform("2");
        int in = orderMapper.insertSelective(order);
        for (int i = 0; i < id.length; i++) {
            classsify classsify = classsifyMapper.selectByPrimaryKey(Integer.parseInt(id[i]));
            orderItem orderItem = new orderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductType(classsify.getName());
            orderItem.setProductImg(classsify.getIcon());
            orderItem.setTodayPrice(classsify.getSettlementPrice());
            orderItem.setUnit(classsify.getMeasure());
            orderItemMapper.insertSelective(orderItem);
        }
        order dataOrder = orderMapper.selectByPrimaryKey(order.getId());
        if(in==1){
            log.debug("开始推送");
            //推送消息给管理员，提醒派单

            List<String> openIds = new ArrayList<>();


            openIds.add("oFPgIw72IEi7KXD7WjNEj9__F_Dc");

            openIds.add("oFPgIw7MovwilW9q955Y7RHrT6CM");

   //        openIds.add(order.getMerchantopenid());
            //杨远量
          //  openIds.add("oFPgIw72IEi7KXD7WjNEj9__F_Dc");
            //黄小姐
         //  openIds.add("oFPgIw7MovwilW9q955Y7RHrT6CM");
            //陆荣康
//          openIds.add("oFPgIw9PIVwv02aCzZ2IX8J8CAHM");
            //张松
//            openIds.add("oFPgIwyIjmu5CENT5Oq5W8NlaU7U");
            //高华健
//          openIds.add("oFPgIwyuCjEIJe80pTC2OEoOe234");
            //谢婉怡
//          openIds.add("oFPgIw01Tadi1p3NYhPydRspiFK4");
            //肖原
      //      openIds.add("oFPgIw_D9SUsvqsD_uA7dDxz3eKs");
            //冯成
//            openIds.add("oFPgIw2-8r79J6aoNrtlhA9EQzn4");
            //王总
//            openIds.add("oFPgIw4m20hoEXIELztoUQM3YdtU");

            //1，配置
            WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
            wxStorage.setAppId("wx8153b9b18ebfa8eb");
            wxStorage.setSecret("c8bf9f0c564f7f44a297054995e6eada");
            String token = gzhMapper.selectByPrimaryKey(3).getAccessToken();
            wxStorage.setAccessToken(token);

            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxStorage);


            for (int i = 0 ;i<openIds.size() ;i++){

                WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
                miniProgram.setAppid("wx578244d5b6022c06");
                miniProgram.setPagePath("/sendOrder/main?id="+dataOrder.getId() );
                //2,推送消息
                WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                        .toUser(openIds.get(i))//要推送的用户openid
                        .templateId("Xc_tnHReR3n1X91cwATTFitTJwgKDGn2YRhpygiA53U")//模版id
                        .miniProgram(miniProgram)
                        .build();
                //3,如果是正式版发送模版消息，这里需要配置你的信息
                templateMessage.addData(new WxMpTemplateData("first", "商家提醒", "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword1", "用户下单了，请及时", "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword2", dataOrder.getUserName(), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword4", dataOrder.getUserPhone(), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword5", dataOrder.getUserArea().substring(dataOrder.getUserArea().indexOf("市")+1,Math.min(dataOrder.getUserArea().indexOf("市")+20,dataOrder.getUserArea().length())), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("remark", "点击派单", "#FF00FF"));
                //templateMessage.addData(new WxMpTemplateData("name2", value2, color2));
                try {
                    wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                } catch (Exception e) {
                    System.out.println("推送失败：" + e.getMessage());
                    e.printStackTrace();
                }
            }

//            String token = gzhMapper.selectByPrimaryKey(3).getAccessToken();
//
//
//            Template template=new Template();
//            template.setTemplate_id("NI3QUdhDLMXCp0AgHryZkirm3gwwf2-YFJV11pJrIko");
//            template.setPage("pages/sendOrder/main?id="+dataOrder.getId());
//            List<TemplateParam> paras=new ArrayList<TemplateParam>();
//            paras.add(new TemplateParam("time3",dataOrder.getOrderVisitTime().substring(0,5)));
//            paras.add(new TemplateParam("character_string1",dataOrder.getOrderNumber()));
//            paras.add(new TemplateParam("thing4","有用户下单了，请及时派单"));
//            paras.add(new TemplateParam("thing2",dataOrder.getUserArea().substring(dataOrder.getUserArea().indexOf("市")+1,Math.min(dataOrder.getUserArea().indexOf("市")+20,dataOrder.getUserArea().length()))));
//            paras.add(new TemplateParam("phone_number5",dataOrder.getUserPhone()));
//            template.setTemplateParamList(paras);
//            String requestUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
//            requestUrl=requestUrl.replace("ACCESS_TOKEN", token);
//
//            List<String> openIds = new ArrayList<>();
//            //欧阳辉
//            openIds.add("osdn25drOI8-6sY9K58zOSCAajOI");
//            //冯多飞
//            openIds.add("osdn25b0tK8-4aguS2xVFa2fxkJc");
//            //肖原
//            openIds.add("osdn25eA1XaqC4oK8sjM-WXIDZwQ");
//            //郭智超
//            openIds.add("osdn25emak1YdPypoWi7XgbMlHiM");
//            //杨远量
//            openIds.add("osdn25R7XC8ovDN14k2vMeV9X5EU");
//            //黄小姐
//            openIds.add("osdn25Ym8McrfpUo-3jVCzKS9700");
//            for (int i = 0 ;i<6 ;i++){
//                template.setTouser(openIds.get(i));
//                net.sf.json.JSONObject jsonResult= CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());
//                if(jsonResult!=null){
//                    System.out.println(jsonResult);
//                    int errorCode=jsonResult.getInt("errcode");
//                    String errorMessage=jsonResult.getString("errmsg");
//                    if(errorCode==0){
//                        log.debug("提醒管理员派单Send Success");
//                    }else{
//                        log.debug("订阅消息发送失败:"+errorCode+","+errorMessage);
//                    }
//                }
//            }
//
//            System.out.println(template.toJSON());

            return true;
        }else {
            return false;
        }
    }











    @Override
    public boolean addImgPath(String path,String number) {
        orderExample oEx = new orderExample();
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andOrderNumberEqualTo(number);
        List<order> orders = orderMapper.selectByExample(oEx);
        orders.get(0).setOrderImg(orders.get(0).getOrderImg()+","+path);
        int i = orderMapper.updateByPrimaryKeySelective(orders.get(0));
        if(i==1){
            return true;
        }else {
            return false;
        }
    }

    /**
     *
     * @Description:
     * 获取用户各状态订单
     * @auther: 欧阳辉
     * @date: 11:36 2020/3/17
     * @param: [orderStatus, openId]
     * @return: java.util.List<cn.itcast.pojo.order>
     *
     */
    @Override
    public List<order> findOrder(String orderStatus, String openId) {
        orderExample oEx = new orderExample();
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        criteria.andOrderStateEqualTo(orderStatus);
        Map<String,String> map = new HashMap<>();
        map.put("openId",openId);
        map.put("state",orderStatus);
        List<order> orders = new ArrayList<>();
        if(orderStatus.equals("进行中")){
            orders= orderMapper.findOrderByStateProceed(openId);
        }else {
            orders = orderMapper.findOrderByState(map);
        }
        for (int i = 0 ; i <orders.size() ;i++){
            orderItemExample oIEx = new orderItemExample();
            orderItemExample.Criteria criteria1 = oIEx.createCriteria();
            criteria1.andOrderIdEqualTo(orders.get(i).getId());
            List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
            orders.get(i).setOrderItems(orderItems);
        }
        return orders;
    }

    /**
     * 功能描述: <br>
     * 〈获取用户订单详情〉
     * @Author: lyy
     * @Date: 2020/7/4 10:07
     * @Param: [orderStatus, openId]
     * @Return: java.util.List<cn.itcast.pojo.order>
     */
    @Override
    public List<order> findUserOrder(String orderStatus, String openId) {
        orderExample oEx = new orderExample();
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        if(!orderStatus.equals(" ")){
            criteria.andOrderStateEqualTo(orderStatus);
        }
        oEx.setOrderByClause("order_time DESC");
        List<order> orders = new ArrayList<>();
        if (orderStatus.equals("已完成")){
            orders=orderMapper.selectUserAccomplish(openId);
        }else {
            orders = orderMapper.selectByExample(oEx);
        }


        for (int i = 0 ; i <orders.size() ;i++){
            orderItemExample oIEx = new orderItemExample();
            orderItemExample.Criteria criteria1 = oIEx.createCriteria();
            criteria1.andOrderIdEqualTo(orders.get(i).getId());
            List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
            orders.get(i).setOrderItems(orderItems);
        }
        return orders;
    }

    @Override
    public Integer productOrder(temporaryOrder temporaryOrder) {
        int i = temporaryOrderMapper.insertSelective(temporaryOrder);
        if(i==1){
            return temporaryOrder.getId();
        }else {
            return 1;
        }
    }

    @Override
    public Integer productOrderItem(temporaryOrderItem temporaryOrderItem) {
        int i = temporaryOrderItemMapper.insertSelective(temporaryOrderItem);
        if(i==1){
            return temporaryOrderItem.getId();
        }else {
            return 1;
        }
    }

    @Override
    public boolean productuploadOrder(String path, Integer orderItemId) {
        temporaryOrderItem temporaryOrderItem = temporaryOrderItemMapper.selectByPrimaryKey(orderItemId);
        temporaryOrderItem.setFilelist(temporaryOrderItem.getFilelist()+","+path);
        int i = temporaryOrderItemMapper.updateByPrimaryKeySelective(temporaryOrderItem);
        if(i==1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean accessoryuploadOrder(String path, Integer orderItemId) {
        temporaryOrderItem temporaryOrderItem = temporaryOrderItemMapper.selectByPrimaryKey(orderItemId);
        temporaryOrderItem.setAccessorylist(temporaryOrderItem.getAccessorylist()+","+path);
        int i = temporaryOrderItemMapper.updateByPrimaryKeySelective(temporaryOrderItem);
        if(i==1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<temporaryOrder> temporaryfindAllOrder(Integer page, Integer limit, String select, String value) {
        temporaryOrderExample temporaryOrderExample = new temporaryOrderExample();
        temporaryOrderExample.Criteria criteria = temporaryOrderExample.createCriteria();
        if(select.equals("recycle")){
            criteria.andRecycleLike("%"+value+"%");
        }else if(select.equals("exploit")){
            criteria.andExploitLike("%"+value+"%");
        }else if(select.equals("client")){
            criteria.andClientLike("%"+value+"%");
        }
        //分页
        PageHelper.startPage(page, limit);
        List<temporaryOrder> temporaryOrders = temporaryOrderMapper.selectByExample(temporaryOrderExample);
        return temporaryOrders;
    }

    @Override
    public List<temporaryOrderItem> temporaryfindOrderItem(Integer orderId) {
        temporaryOrderItemExample temporaryOrderItemExample = new temporaryOrderItemExample();
        temporaryOrderItemExample.Criteria criteria = temporaryOrderItemExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        return temporaryOrderItemMapper.selectByExample(temporaryOrderItemExample);

    }

    @Override
    public boolean addRecharge(recharge recharge) {
        int i = rechargeMapper.insertSelective(recharge);
        if(i==1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean updateRecharge(recharge recharge) {
        //获取记录信息
        rechargeExample rEx = new rechargeExample();
        rechargeExample.Criteria criteria = rEx.createCriteria();
        criteria.andRechargeNumberEqualTo(recharge.getRechargeNumber());
        List<cn.itcast.pojo.recharge> recharges = rechargeMapper.selectByExample(rEx);
        if(recharges.isEmpty()){
            return false;
        }else {
            //修改记录状态
            recharge recharge1 = recharges.get(0);
            recharge1.setBillState(recharge.getBillState());
            recharge1.setPayState(recharge.getPayState());
            int i = rechargeMapper.updateByPrimaryKeySelective(recharge1);
            if(i==1){
                //修改账户金额
                accountExample aEx = new accountExample();
                accountExample.Criteria criteria1 = aEx.createCriteria();
                criteria1.andOpenIdEqualTo(recharge1.getOpenId());
//                criteria1.andAccountTypeidEqualTo(1);
                List<account> accounts = accountMapper.selectByExample(aEx);
                if(accounts.isEmpty()){
                    return false;
                }else {
                    account account = accounts.get(0);
                    account.setAccountMoneyBalance(account.getAccountMoneyBalance()+recharge1.getRechargeSum());
                    account.setAccountMoneyRental(account.getAccountMoneyRental()+recharge1.getRechargeSum());
                    accountMapper.updateByPrimaryKeySelective(account);
                    //创建收益记录
                    earnings earnings = new earnings();
                    earnings.setAccountId(account.getAccountId());
                    earnings.setName(account.getAccountName());
                    earnings.setPhone(account.getAccountPhone());
                    earnings.setOpenid(account.getOpenId());
                    earnings.setSource("微信充值");
                    earnings.setNumber(getOrderIdByTime());
                    earnings.setNum(recharge1.getRechargeSum());
                    earnings.setState("已到账");
                    earnings.setEarningsExplain("微信充值");
                    int i1 = earningsMapper.insertSelective(earnings);
                    if(i1 == 1){
                        log.debug("收益记录成功");
                    }else {

                        log.debug("收益记录失败");
                    }
                    return true;
                }
            }else {
                return false;
            }
        }

    }

    @Override
    public List<order> findStatusOrder(String orderStatus) {
        orderExample oEx = new orderExample();
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andOrderStateEqualTo(orderStatus);
        List<order> orders = orderMapper.selectByExample(oEx);
        for (int i = 0 ; i <orders.size() ;i++){
            orderItemExample oIEx = new orderItemExample();
            orderItemExample.Criteria criteria1 = oIEx.createCriteria();
            criteria1.andOrderIdEqualTo(orders.get(i).getId());
            List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
            orders.get(i).setOrderItems(orderItems);

            orderExample orderExample = new orderExample();
            orderExample.Criteria exampleCriteria = orderExample.createCriteria();
            exampleCriteria.andIdEqualTo(orders.get(i).getId());
            List<order> orderList = orderMapper.selectByExample(orderExample);
            if(orderList.size()!=0 && orderList.get(0).getDispatchOpenId()!=null&& !orderList.get(0).getDispatchOpenId().equals("")){
                userExample userExample = new userExample();
                userExample.Criteria userCrt = userExample.createCriteria();
                userCrt.andOpenIdEqualTo(orderList.get(0).getDispatchOpenId());
                List<user> userList = userMapper.selectByExample(userExample);
                orders.get(i).setDispatch_order_name(userList.get(0).getUserName());
            }else{
                orders.get(i).setDispatch_order_name("大黄牛后台");
            }
        }
        return orders;
    }

    @Override
    public Map<String, List<order>> findDistributionOrder(String openId) {

        Map<String,List<order>> orderMap = new HashMap<>();
        //一级分销订单
        userExample uEx = new userExample();
        userExample.Criteria criteria = uEx.createCriteria();
        criteria.andUserOneDistributionEqualTo(openId);
        List<user> users = userMapper.selectByExample(uEx);
        List<order> oneList = new ArrayList<>();
        for (int i = 0;i<users.size();i++){
            orderExample oEx = new orderExample();
            orderExample.Criteria criteria1 = oEx.createCriteria();
            criteria1.andOpenIdEqualTo(users.get(i).getOpenId());
            List<String> values = new ArrayList<>();
            values.add("已完成");
            values.add("已评价");
            criteria1.andOrderStateIn(values);
            List<order> orders = orderMapper.selectByExample(oEx);
            for(int j = 0 ; j<orders.size();j++){
                oneList.add(orders.get(j));
            }
        }
        orderMap.put("one",oneList);


        List<order> twoList = new ArrayList<>();
        //二级分销订单
        userExample twouEx = new userExample();
        userExample.Criteria criteria3 = twouEx.createCriteria();
        criteria3.andUserTwoDistributionEqualTo(openId);
        List<user> twousers = userMapper.selectByExample(twouEx);

        for (int i = 0;i<twousers.size();i++){
            orderExample oEx = new orderExample();
            orderExample.Criteria criteria1 = oEx.createCriteria();
            criteria1.andOpenIdEqualTo(twousers.get(i).getOpenId());
            List<String> values = new ArrayList<>();
            values.add("已完成");
            values.add("已评价");
            criteria1.andOrderStateIn(values);
            List<order> orders = orderMapper.selectByExample(oEx);
            for(int j = 0 ; j<orders.size();j++){
                twoList.add(orders.get(j));
            }
        }
        orderMap.put("two",twoList);

        return orderMap;
    }

    @Override
    public Integer findUserUnfinishOrder(String openId) {
        orderExample oEx = new orderExample();
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        List<String> value = new ArrayList<>();
        value.add("待派单");
        value.add("待接单");
        value.add("进行中");
        criteria.andOrderStateIn(value);
        List<order> orders = orderMapper.selectByExample(oEx);
        if(orders.isEmpty()){
            return 0;
        }else{
            return orders.get(0).getId();
        }
    }

    @Override
    public List<order> getYesterdayOrder() {
        return orderMapper.getYesterdayOrder();
    }

    /**
     *
     * @Description: 查看每日订单情况
     *
     * @auther: 张松
     * @date: 9:20 2020/7/18
     * @param: []
     * @return: java.util.List<cn.itcast.pojo.order>
     *
     */
    public List<order> getEveryDayOrder(Integer intDate){
        return orderMapper.getEveryDayOrder(intDate);
    }


    @Override
    public List<orderItem> getYesterdayOrderWeightAndMoney() {
        return orderItemMapper.getYesterdayOrderWeightAndMoney();
    }

    @Override
    public List<orderItem> getYesterdayOrderWeightAndMoneyAndProductType() {
        return  orderItemMapper.getYesterdayOrderWeightAndMoneyAndProductType();
    }

    public List<orderItem> getEverydayOrderWeightAndMoneyAndProductType(int everyDay) {
        return orderItemMapper.getEverydayOrderWeightAndMoneyAndProductType(everyDay);
    }

    @Override
    public String userPreviousHorseman(String openId) {
        return orderMapper.userPreviousHorseman(openId);
    }


    public static Map<String,Double> getLngAndLat(String address){
        Map<String,Double> map=new HashMap<String, Double>();
        String url = "http://api.map.baidu.com/geocoder/v2/?address="+address+"&output=json&ak=14fN9rWBjnBw4LGzGe7PVNtf";
        String json = loadJSON(url);
        JSONObject obj = JSONObject.fromObject(json);
        if(obj.get("status").toString().equals("0")){
            double lng=obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
            double lat=obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
            map.put("lng", lng);
            map.put("lat", lat);
            //System.out.println("经度："+lng+"---纬度："+lat);
        }else{
            //System.out.println("未找到相匹配的经纬度！");
        }
        return map;
    }

    public static String loadJSON (String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream()));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }


    //最新订单结束10条
    public List<order> toporderimpl() {
        return orderMapper.toporder();
    }

    //顺丰下单
    public int sfadd(sforder sforder){return orderMapper.sfadd(sforder); }

    //id获取顺丰订单
    public List<sforder>listsfquery(String openid){return orderMapper.listsfquery(openid);}

    //id查询最新下单一条数据
    public sforder toponeidquery(String openid){return  orderMapper.toponeidquerymapp(openid);}

    //顺丰取消下单
    public int sfcancelmapp(sforder sforder){return  orderMapper.sfcancelmapp(sforder);}

    //删除顺丰已取消订单
    public int deletesfopenidmapp(sforder sforder){return  orderMapper.deletesfopenid(sforder);}

    //顺丰修改订单变化
    public int updatesforder(sforder sforder){return  orderMapper.updatesforder(sforder);}

    //顺丰修改重量运费清单
    public int updatesffreightmapp(sforder sforder){return orderMapper.updatesffreight(sforder);}

    //顺丰路由推送到达地址
    public int updateRoutepush(sforder sforder){return  orderMapper.updateRoutepushmapp(sforder); }

    public sforder selectorderid(String orderid){return orderMapper.selectorderid(orderid);}

    //赠送环保金
    public int updatemoney(account account){return orderMapper.updatemoney(account);}
    //查询账户总额
    public account selemoneycount(account account){return orderMapper.selemoneycount(account);}

    //新增快递收益
    public int addearnings(earnings earnings){return orderMapper.addearnings(earnings);}




}
